package com.mallcloud.mall.auth.handler;

import com.mallcloud.mall.common.core.constant.CacheConstants;
import com.mallcloud.mall.common.core.constant.SecurityConstants;
import com.mallcloud.mall.common.core.util.KeyStrResolver;
import com.mallcloud.mall.common.security.handler.AuthenticationSuccessHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录操作次数锁定清楚功能
 */
@Slf4j
@Component
@AllArgsConstructor
public class MallAuthenticationSuccessLockEventHandler implements AuthenticationSuccessHandler {

	private final RedisTemplate<String, String> redisTemplate;

	private final KeyStrResolver tenantKeyStrResolver;

	/**
	 * 处理登录成功方法
	 * <p>
	 * 获取到登录的authentication 对象
	 * @param authentication 登录对象
	 * @param request 请求
	 * @param response 返回
	 */
	@Async
	@Override
	public void handle(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
		if (!request.getRequestURI().contains(SecurityConstants.OAUTH_TOKEN_URL)) {
			return;
		}

		String username = authentication.getName();
		String key = String.format("%s:%s:%s", CacheConstants.LOGIN_ERROR_TIMES, tenantKeyStrResolver.key(), username);
		redisTemplate.delete(key);
	}

}
